package com.zz.cc.owner.app;

import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.zz.cc.owner.R;
import com.zz.cc.owner.TitleBaseActivity;

public class WebkitActivity extends TitleBaseActivity {
	
	private static final String INDEX_TITLE = "title";
	private static final String INDEX_URL = "url";
	
	private WebView mWebView;
	private String mInitTitle;
	private String mInitUrl;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData(getIntent());
		
		setContentView(R.layout.activity_webkit);
		initUI();
	}
	
	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		releaseWebView();
	}
	
	@Override
	public void onBackPressed() {
		if(mWebView.canGoBack()) {
			mWebView.goBack();
			return;
		}
		
		super.onBackPressed();
	}
	
	private void initData(Intent intent) {
		mInitTitle = intent.getStringExtra(INDEX_TITLE);
		mInitUrl = intent.getStringExtra(INDEX_URL);
	}
	
	private void initUI() {
		mWebView = (WebView) findViewById(R.id.webkit_webview);
		mWebView.getSettings().setCacheMode(WebSettings.LOAD_NORMAL);
		mWebView.getSettings().setBlockNetworkImage(true);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.setWebChromeClient(new WebkitChromeClient());
		mWebView.setWebViewClient(new WebkitWebViewClient());
		
		setCurrentTitle(mInitTitle);
		loadUrl(mInitUrl);
	}
	
	private class WebkitChromeClient extends WebChromeClient {
		
		@Override
		public void onReceivedTitle(WebView webView, String title) {
			setCurrentTitle(title);
		}
		
		@Override
		public void onProgressChanged(WebView webView, int newProgress) {
		}
	}
	
	private class WebkitWebViewClient extends WebViewClient {
		@Override
	    public boolean shouldOverrideUrlLoading(WebView webview, String url) {
			loadUrl(url);
			return true;
		}
	}
	
	private void loadUrl(String url) {
		mWebView.stopLoading();
		mWebView.clearView();
		mWebView.loadUrl(url);
	}
	
	private void releaseWebView() {
		mWebView.stopLoading();
		mWebView.clearView();
		mWebView.destroy();
		
	}

}